<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\MoneyTransaction;
use App\Models\MoneyCategory;
use App\Models\MoneySubCategory;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

class StatisticsController extends Controller
{
    /**
     * 生成缓存键
     */
    private function generateCacheKey($type, $params)
    {
        $prefix = config('statistics.cache.key_prefix', 'stats');
        $keyParts = [$prefix, $type];
        
        foreach ($params as $key => $value) {
            $keyParts[] = $key . '_' . $value;
        }
        
        return implode(':', $keyParts);
    }

    /**
     * 获取缓存数据
     */
    private function getCachedData($cacheKey, $callback)
    {
        // 检查是否启用缓存
        if (!config('statistics.cache.enabled', true)) {
            return $callback();
        }
        
        $ttl = config('statistics.cache.ttl', 1800); // 默认30分钟
        $store = config('statistics.cache.store'); // 可选的专用缓存存储
        
        if ($store) {
            return Cache::store($store)->remember($cacheKey, $ttl, $callback);
        } else {
            return Cache::remember($cacheKey, $ttl, $callback);
        }
    }
    /**
     * 显示统计页面
     */
    public function index()
    {
        $user = Auth::user();
        $moneyBook = $user->getCurrentDefaultBook();

        if (!$moneyBook) {
            return redirect()->route('user.books.index')->with('error', '请先创建或选择一个账本');
        }

        return view('statistics.index', [
            'title' => '统计分析',
            'moneyBook' => $moneyBook,
        ]);
    }

    /**
     * 获取收支趋势数据
     */
    public function getTrendData(Request $request)
    {
        try {
            $user = Auth::user();
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到账本数据'
                ]);
            }

            $type = $request->get('type', 'daily'); // daily, weekly, monthly
            $startDate = $request->get('start_date');
            $endDate = $request->get('end_date');

            // 设置默认时间范围
            if (!$startDate || !$endDate) {
                switch ($type) {
                    case 'weekly':
                        $startDate = Carbon::now()->subWeeks(12)->startOfWeek();
                        $endDate = Carbon::now()->endOfWeek();
                        break;
                    case 'monthly':
                        $startDate = Carbon::now()->subMonths(12)->startOfMonth();
                        $endDate = Carbon::now()->endOfMonth();
                        break;
                    default: // daily
                        $startDate = Carbon::now()->subDays(30);
                        $endDate = Carbon::now();
                        break;
                }
            } else {
                $startDate = Carbon::parse($startDate);
                $endDate = Carbon::parse($endDate);
            }

            // 生成缓存键
            $cacheKey = $this->generateCacheKey('trend', [
                'book_id' => $moneyBook->id,
                'type' => $type,
                'start_date' => $startDate->format('Y-m-d'),
                'end_date' => $endDate->format('Y-m-d')
            ]);

            // 尝试从缓存获取数据
            $data = $this->getCachedData($cacheKey, function() use ($moneyBook, $type, $startDate, $endDate) {
                return $this->generateTrendData($moneyBook->id, $type, $startDate, $endDate);
            });

            return response()->json([
                'success' => true,
                'data' => $data
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取趋势数据失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取分类统计数据
     */
    public function getCategoryData(Request $request)
    {
        try {
            $user = Auth::user();
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到账本数据'
                ]);
            }

            $type = $request->get('transaction_type', 'expense'); // income, expense
            $level = $request->get('level', 1); // 1: 一级分类, 2: 二级分类
            $startDate = $request->get('start_date', Carbon::now()->startOfMonth());
            $endDate = $request->get('end_date', Carbon::now()->endOfMonth());

            $startDate = Carbon::parse($startDate);
            $endDate = Carbon::parse($endDate);

            // 生成缓存键
            $cacheKey = $this->generateCacheKey('category', [
                'book_id' => $moneyBook->id,
                'type' => $type,
                'level' => $level,
                'start_date' => $startDate->format('Y-m-d'),
                'end_date' => $endDate->format('Y-m-d')
            ]);

            // 尝试从缓存获取数据
            $data = $this->getCachedData($cacheKey, function() use ($moneyBook, $type, $level, $startDate, $endDate) {
                return $this->generateCategoryData($moneyBook->id, $type, $level, $startDate, $endDate);
            });

            return response()->json([
                'success' => true,
                'data' => $data
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取分类数据失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 生成分类统计数据
     */
    private function generateCategoryData($bookId, $type, $level, $startDate, $endDate)
    {
        if ($level == 2) {
            // 查询二级分类数据，同时获取一级分类名称
            $categoryData = MoneyTransaction::where('money_transactions.book_id', $bookId)
                ->where('money_transactions.type', MoneyCategory::type_key_map[$type])
                ->whereBetween('transaction_date', [$startDate, $endDate])
                ->join('money_sub_categories', 'money_transactions.sub_category_id', '=', 'money_sub_categories.id')
                ->join('money_categories', 'money_sub_categories.category_id', '=', 'money_categories.id')
                ->select(
                    'money_sub_categories.id as category_id',
                    'money_categories.id as parent_category_id',
                    'money_categories.name as parent_category_name',
                    'money_sub_categories.name as sub_category_name',
                    DB::raw('CONCAT(money_categories.name, "-", money_sub_categories.name) as category_name'),
                    DB::raw('SUM(money_transactions.amount) as total_amount'),
                    DB::raw('COUNT(money_transactions.id) as transaction_count')
                )
                ->groupBy('money_sub_categories.id', 'money_categories.id', 'money_categories.name', 'money_sub_categories.name')
                ->orderBy('total_amount', 'desc')
                ->get();
        } else {
            // 查询一级分类数据
            $categoryData = MoneyTransaction::where('money_transactions.book_id', $bookId)
                ->where('money_transactions.type', MoneyCategory::type_key_map[$type])
                ->whereBetween('transaction_date', [$startDate, $endDate])
                ->join('money_categories', 'money_transactions.category_id', '=', 'money_categories.id')
                ->select(
                    'money_categories.id as category_id',
                    'money_categories.name as category_name',
                    DB::raw('SUM(money_transactions.amount) as total_amount'),
                    DB::raw('COUNT(money_transactions.id) as transaction_count')
                )
                ->groupBy('money_categories.id', 'money_categories.name')
                ->orderBy('total_amount', 'desc')
                ->get();
        }

        $totalAmount = $categoryData->sum('total_amount');

        $formattedData = $categoryData->map(function($item) use ($totalAmount, $level) {
            $result = [
                'category_id' => $item->category_id,
                'category_name' => $item->category_name,
                'amount' => $item->total_amount,
                'count' => $item->transaction_count,
                'percentage' => $totalAmount > 0 ? round(($item->total_amount / $totalAmount) * 100, 2) : 0
            ];

            // 如果是二级分类，添加父分类ID
            if ($level == 2) {
                $result['parent_category_id'] = $item->parent_category_id;
            }

            return $result;
        });

        return [
            'categories' => $formattedData,
            'total_amount' => $totalAmount,
            'type' => $type,
            'level' => $level,
            'period' => [
                'start' => $startDate->format('Y-m-d'),
                'end' => $endDate->format('Y-m-d')
            ]
        ];
    }

    /**
     * 获取月度对比数据
     */
    public function getMonthlyComparison(Request $request)
    {
        try {
            $user = Auth::user();
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到账本数据'
                ]);
            }

            $months = $request->get('months', 6); // 默认显示6个月
            $year = $request->get('year'); // 指定年份

            // 生成缓存键
            $cacheKey = $this->generateCacheKey('monthly_comparison', [
                'book_id' => $moneyBook->id,
                'months' => $months,
                'year' => $year
            ]);

            // 尝试从缓存获取数据
            $data = $this->getCachedData($cacheKey, function() use ($moneyBook, $months, $year) {
                return $this->generateMonthlyComparisonData($moneyBook->id, $months, $year);
            });

            return response()->json([
                'success' => true,
                'data' => $data
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取月度对比数据失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 生成月度对比数据
     */
    private function generateMonthlyComparisonData($bookId, $months, $year)
    {
        $data = [];

        if ($year) {
            // 如果指定了年份，返回该年份的12个月数据
            for ($month = 1; $month <= 12; $month++) {
                $date = Carbon::createFromDate($year, $month, 1);
                $startOfMonth = $date->copy()->startOfMonth();
                $endOfMonth = $date->copy()->endOfMonth();

                $income = MoneyTransaction::where('book_id', $bookId)
                    ->where('type', MoneyCategory::TYPE_INCOME)
                    ->whereBetween('transaction_date', [$startOfMonth, $endOfMonth])
                    ->sum('amount');

                $expense = MoneyTransaction::where('book_id', $bookId)
                    ->where('type', MoneyCategory::TYPE_EXPENSE)
                    ->whereBetween('transaction_date', [$startOfMonth, $endOfMonth])
                    ->sum('amount');

                $data[] = [
                    'month' => $date->format('Y-m'),
                    'month_name' => $date->format('Y年m月'),
                    'income' => $income,
                    'expense' => $expense,
                    'net' => $income - $expense
                ];
            }
        } else {
            // 原有逻辑：返回最近N个月的数据
            for ($i = $months - 1; $i >= 0; $i--) {
                $date = Carbon::now()->subMonths($i);
                $startOfMonth = $date->copy()->startOfMonth();
                $endOfMonth = $date->copy()->endOfMonth();

                $income = MoneyTransaction::where('book_id', $bookId)
                    ->where('type', MoneyCategory::TYPE_INCOME)
                    ->whereBetween('transaction_date', [$startOfMonth, $endOfMonth])
                    ->sum('amount');

                $expense = MoneyTransaction::where('book_id', $bookId)
                    ->where('type', MoneyCategory::TYPE_EXPENSE)
                    ->whereBetween('transaction_date', [$startOfMonth, $endOfMonth])
                    ->sum('amount');

                $data[] = [
                    'month' => $date->format('Y-m'),
                    'month_name' => $date->format('Y年m月'),
                    'income' => $income,
                    'expense' => $expense,
                    'net' => $income - $expense
                ];
            }
        }

        return $data;
    }

    /**
     * 生成分类详情数据
     */
    private function generateTrendData($bookId, $type, $startDate, $endDate)
    {
        $data = [
            'labels' => [],
            'income' => [],
            'expense' => []
        ];

        switch ($type) {
            case 'weekly':
                $current = $startDate->copy();
                $weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

                while ($current <= $endDate) {
                    $income = MoneyTransaction::where('book_id', $bookId)
                        ->where('type', MoneyCategory::TYPE_INCOME)
                        ->whereDate('transaction_date', $current)
                        ->sum('amount');

                    $expense = MoneyTransaction::where('book_id', $bookId)
                        ->where('type', MoneyCategory::TYPE_EXPENSE)
                        ->whereDate('transaction_date', $current)
                        ->sum('amount');

                    // 获取星期几（1=周一，7=周日）
                    $dayOfWeek = $current->dayOfWeekIso;
                    $data['labels'][] = $weekDays[$dayOfWeek - 1];
                    $data['income'][] = $income;
                    $data['expense'][] = $expense;

                    $current->addDay();
                }
                break;

            case 'monthly':
                $current = $startDate->copy();
                // 确保只循环到当月的最后一天
                $monthEnd = $startDate->copy()->endOfMonth();
                $actualEndDate = $endDate->lt($monthEnd) ? $endDate : $monthEnd;

                while ($current <= $actualEndDate) {
                    $income = MoneyTransaction::where('book_id', $bookId)
                        ->where('type', MoneyCategory::TYPE_INCOME)
                        ->whereDate('transaction_date', $current)
                        ->sum('amount');

                    $expense = MoneyTransaction::where('book_id', $bookId)
                        ->where('type', MoneyCategory::TYPE_EXPENSE)
                        ->whereDate('transaction_date', $current)
                        ->sum('amount');

                    // 显示日期（根据实际月份天数）
                    $data['labels'][] = $current->day;
                    $data['income'][] = $income;
                    $data['expense'][] = $expense;

                    $current->addDay();
                }
                break;

            case 'yearly':
                $current = $startDate->copy();
                while ($current <= $endDate) {
                    $monthStart = $current->copy()->startOfMonth();
                    $monthEnd = $current->copy()->endOfMonth();

                    $income = MoneyTransaction::where('book_id', $bookId)
                        ->where('type', MoneyCategory::TYPE_INCOME)
                        ->whereBetween('transaction_date', [$monthStart, $monthEnd])
                        ->sum('amount');

                    $expense = MoneyTransaction::where('book_id', $bookId)
                        ->where('type', MoneyCategory::TYPE_EXPENSE)
                        ->whereBetween('transaction_date', [$monthStart, $monthEnd])
                        ->sum('amount');

                    // 显示月份（1月、2月等）
                    $data['labels'][] = $current->month . '月';
                    $data['income'][] = $income;
                    $data['expense'][] = $expense;

                    $current->addMonth();
                }
                break;

            default: // daily
                $current = $startDate->copy();
                while ($current <= $endDate) {
                    $income = MoneyTransaction::where('book_id', $bookId)
                        ->where('type', MoneyCategory::TYPE_INCOME)
                        ->whereDate('transaction_date', $current)
                        ->sum('amount');

                    $expense = MoneyTransaction::where('book_id', $bookId)
                        ->where('type', MoneyCategory::TYPE_EXPENSE)
                        ->whereDate('transaction_date', $current)
                        ->sum('amount');

                    $data['labels'][] = $current->format('m/d');
                    $data['income'][] = $income;
                    $data['expense'][] = $expense;

                    $current->addDay();
                }
                break;
        }

        return $data;
    }

    /**
     * 显示分类详情页面
     */
    public function categoryDetail(Request $request)
    {
        $user = Auth::user();
        $moneyBook = $user->getCurrentDefaultBook();

        if (!$moneyBook) {
            return redirect()->route('user.books.index')->with('error', '请先创建或选择一个账本');
        }

        $categoryId = $request->get('category_id');
        $categoryType = $request->get('type', 'expense'); // expense 或 income
        $categoryLevel = $request->get('level', 1); // 1: 一级分类, 2: 二级分类
        $periodType = $request->get('period_type', 'month'); // week, month, year
        $periodValue = $request->get('period_value', Carbon::now()->format('Y-m')); // 具体的周期值

        // 根据分类ID获取分类名称
        if ($categoryLevel == 1) {
            $category = MoneyCategory::find($categoryId);
            $categoryName = $category ? $category->name : '未知分类';
        } else {
            $subCategory = MoneySubCategory::find($categoryId);
            $categoryName = $subCategory ? $subCategory->category->name . '-' . $subCategory->name : '未知分类';
        }

        return view('statistics.category-detail', [
            'title' => '分类统计 - ' . $categoryName,
            'moneyBook' => $moneyBook,
            'categoryId' => $categoryId,
            'categoryName' => $categoryName,
            'categoryType' => $categoryType,
            'categoryLevel' => $categoryLevel,
            'periodType' => $periodType,
            'periodValue' => $periodValue,
        ]);
    }

    /**
     * 获取分类详情数据
     */
    public function getCategoryDetailData(Request $request)
    {
        try {
            $user = Auth::user();
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到账本数据'
                ]);
            }

            $categoryId = $request->get('category_id');
            $categoryType = $request->get('type', 'expense');
            $categoryLevel = $request->get('level', 1);
            $periodType = $request->get('period_type', 'month');
            $periodValue = $request->get('period_value', Carbon::now()->format('Y-m'));

            // 生成缓存键
            $cacheKey = $this->generateCacheKey('category_detail', [
                'book_id' => $moneyBook->id,
                'category_id' => $categoryId,
                'type' => $categoryType,
                'level' => $categoryLevel,
                'period_type' => $periodType,
                'period_value' => $periodValue
            ]);

            // 尝试从缓存获取数据
            $data = $this->getCachedData($cacheKey, function() use ($moneyBook, $categoryId, $categoryType, $categoryLevel, $periodType, $periodValue) {
                return $this->generateCategoryDetailData($moneyBook->id, $categoryId, $categoryType, $categoryLevel, $periodType, $periodValue);
            });

            return response()->json([
                'success' => true,
                'data' => $data
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取分类详情数据失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 生成分类详情数据
     */
    private function generateCategoryDetailData($bookId, $categoryId, $categoryType, $categoryLevel, $periodType, $periodValue)
    {
        // 根据周期类型计算时间范围
        list($startDate, $endDate) = $this->calculateDateRange($periodType, $periodValue);

        // 根据分类ID获取分类名称
        if ($categoryLevel == 1) {
            $category = MoneyCategory::find($categoryId);
            $categoryName = $category ? $category->name : null;
        } else {
            $subCategory = MoneySubCategory::find($categoryId);
            $categoryName = $subCategory ? $subCategory->category->name . '-' . $subCategory->name : null;
        }

        if (!$categoryName) {
            throw new \Exception('分类不存在');
        }

        // 获取分类统计汇总数据
        $summaryData = $this->getCategorySummaryData($bookId, $categoryId, $categoryType, $categoryLevel, $startDate, $endDate);

        // 获取记账记录
        $recordsData = $this->getCategoryRecordsData($bookId, $categoryId, $categoryType, $categoryLevel, $startDate, $endDate);

        // 获取趋势数据
        $trendData = $this->getCategoryTrendData($bookId, $categoryId, $categoryType, $categoryLevel, $startDate, $endDate);

        // 获取二级分类数据（仅一级分类时）
        $subcategoryData = [];
        if ($categoryLevel == 1) {
            $subcategoryData = $this->getSubcategoryData($bookId, $categoryId, $categoryType, $startDate, $endDate);
        }

        return [
            'summary' => $summaryData,
            'records' => $recordsData,
            'trend' => $trendData,
            'subcategories' => $subcategoryData
        ];
    }

    /**
     * 根据周期类型计算时间范围
     */
    private function calculateDateRange($periodType, $periodValue)
    {
        switch ($periodType) {
            case 'week':
                // 周格式: 2024-01-1 (年-月-周数)
                $parts = explode('-', $periodValue);
                if (count($parts) === 3) {
                    $year = (int)$parts[0];
                    $month = (int)$parts[1];
                    $weekInMonth = (int)$parts[2];

                    // 计算该月第一天
                    $firstDayOfMonth = Carbon::create($year, $month, 1);

                    // 找到该月第一个周一
                    $firstMonday = $firstDayOfMonth->copy();
                    $dayOfWeek = $firstDayOfMonth->dayOfWeek; // 0=周日, 1=周一, ..., 6=周六
                    if ($dayOfWeek !== 1) { // 如果第一天不是周一
                        $daysToMonday = $dayOfWeek === 0 ? 1 : (8 - $dayOfWeek);
                        $firstMonday->addDays($daysToMonday);
                    }

                    // 计算指定周的开始日期
                    $startDate = $firstMonday->copy()->addWeeks($weekInMonth - 1);
                    $endDate = $startDate->copy()->addDays(6);
                } else {
                    // 格式错误，默认当前周
                    $startDate = Carbon::now()->startOfWeek();
                    $endDate = Carbon::now()->endOfWeek();
                }
                break;
            case 'month':
                // 月格式: 2024-01
                $startDate = Carbon::createFromFormat('Y-m', $periodValue)->startOfMonth();
                $endDate = Carbon::createFromFormat('Y-m', $periodValue)->endOfMonth();
                break;
            case 'year':
                // 年格式: 2024
                $startDate = Carbon::createFromFormat('Y', $periodValue)->startOfYear();
                $endDate = Carbon::createFromFormat('Y', $periodValue)->endOfYear();
                break;
            default:
                // 默认当前月
                $startDate = Carbon::now()->startOfMonth();
                $endDate = Carbon::now()->endOfMonth();
        }

        return [$startDate, $endDate];
    }

    /**
     * 获取分类汇总数据
     */
    private function getCategorySummaryData($bookId, $categoryId, $categoryType, $categoryLevel, $startDate, $endDate)
    {
        $query = MoneyTransaction::where('book_id', $bookId)
            ->where('type', MoneyCategory::type_key_map[$categoryType])
            ->whereBetween('transaction_date', [$startDate, $endDate]);

        if ($categoryLevel == 1) {
            $query->where('category_id', $categoryId);
        } else {
            $query->where('sub_category_id', $categoryId);
        }

        $totalAmount = $query->sum('amount');
        $totalCount = $query->count();
        $avgAmount = $totalCount > 0 ? $totalAmount / $totalCount : 0;

        return [
            'total_amount' => $totalAmount,
            'total_count' => $totalCount,
            'avg_amount' => $avgAmount
        ];
    }

    /**
     * 获取分类记录数据
     */
    private function getCategoryRecordsData($bookId, $categoryId, $categoryType, $categoryLevel, $startDate, $endDate)
    {
        $query = MoneyTransaction::where('book_id', $bookId)
            ->where('type', MoneyCategory::type_key_map[$categoryType])
            ->whereBetween('transaction_date', [$startDate, $endDate]);

        if ($categoryLevel == 1) {
            $query->where('category_id', $categoryId);
        } else {
            $query->where('sub_category_id', $categoryId);
        }

        $records = $query->with(['category', 'subCategory'])
            ->orderBy('transaction_date', 'desc')
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function($record) {
                return [
                    'id' => $record->id,
                    'description' => $record->description,
                    'amount' => $record->amount,
                    'transaction_date' => $record->transaction_date->format('Y-m-d H:i'),
                    'category_name' => $record->category->name,
                    'sub_category_name' => $record->subCategory ? $record->subCategory->name : null,
                    'type' => $record->type
                ];
            });

        return $records;
    }

    /**
     * 获取分类趋势数据
     */
    private function getCategoryTrendData($bookId, $categoryId, $categoryType, $categoryLevel, $startDate, $endDate)
    {
        $data = [
            'labels' => [],
            'amounts' => []
        ];

        // 判断时间跨度来决定统计粒度
        $daysDiff = $startDate->diffInDays($endDate);

        if ($daysDiff > 60) {
            // 年统计：按月统计
            $current = $startDate->copy()->startOfMonth();
            while ($current <= $endDate) {
                $monthStart = $current->copy()->startOfMonth();
                $monthEnd = $current->copy()->endOfMonth();

                // 确保不超过结束日期
                if ($monthEnd > $endDate) {
                    $monthEnd = $endDate->copy();
                }

                $query = MoneyTransaction::where('book_id', $bookId)
                    ->where('type', MoneyCategory::type_key_map[$categoryType])
                    ->whereBetween('transaction_date', [$monthStart, $monthEnd]);

                if ($categoryLevel == 1) {
                    $query->where('category_id', $categoryId);
                } else {
                    $query->where('sub_category_id', $categoryId);
                }

                $amount = $query->sum('amount');
                $data['labels'][] = $current->format('Y-m');
                $data['amounts'][] = $amount;

                $current->addMonth();
            }
        } else {
            // 月统计和周统计：按天统计
            $current = $startDate->copy();
            while ($current <= $endDate) {
                $query = MoneyTransaction::where('book_id', $bookId)
                    ->where('type', MoneyCategory::type_key_map[$categoryType])
                    ->whereDate('transaction_date', $current);

                if ($categoryLevel == 1) {
                    $query->where('category_id', $categoryId);
                } else {
                    $query->where('sub_category_id', $categoryId);
                }

                $amount = $query->sum('amount');
                $data['labels'][] = $current->format('Y-m-d');
                $data['amounts'][] = $amount;

                $current->addDay();
            }
        }

        return $data;
    }

    /**
     * 获取二级分类数据
     */
    private function getSubcategoryData($bookId, $categoryId, $categoryType, $startDate, $endDate)
    {
        $subcategoryData = MoneyTransaction::where('money_transactions.book_id', $bookId)
            ->where('money_transactions.type', MoneyCategory::type_key_map[$categoryType])
            ->whereBetween('transaction_date', [$startDate, $endDate])
            ->join('money_categories', 'money_transactions.category_id', '=', 'money_categories.id')
            ->leftJoin('money_sub_categories', 'money_transactions.sub_category_id', '=', 'money_sub_categories.id')
            ->where('money_categories.id', $categoryId)
            ->select(
                'money_sub_categories.id',
                'money_sub_categories.name as sub_category_name',
                DB::raw('SUM(money_transactions.amount) as total_amount'),
                DB::raw('COUNT(money_transactions.id) as transaction_count')
            )
            ->groupBy('money_sub_categories.id', 'money_sub_categories.name')
            ->orderBy('total_amount', 'desc')
            ->get();

        $totalAmount = $subcategoryData->sum('total_amount');

        return $subcategoryData->map(function($item) use ($totalAmount) {
            return [
                'id' => $item->id,
                'name' => $item->sub_category_name ?: '未分类',
                'amount' => $item->total_amount,
                'count' => $item->transaction_count,
                'percentage' => $totalAmount > 0 ? round(($item->total_amount / $totalAmount) * 100, 2) : 0
            ];
        });
    }
}
